import time

import pygame


class ResourceManager:
    """
    图片资源管理器
    避免同一个图片文件被重复创建成多个surface而浪费内存
    """

    def __init__(self):
        self.surface_pool = dict()
        self.surface_light_pool = dict()

    def get_surface(self, file_path):
        """
        获取普通surface
        """
        # 如果图片已加载，直接返回surface
        if file_path in self.surface_pool:
            return self.surface_pool[file_path]
        # 图片第一次加载
        surface = pygame.image.load(file_path).convert_alpha()
        self.surface_pool[file_path] = surface
        return surface

    def get_surface_list(self, file_path_list):
        """
        批量加载surface
        """
        surface_list = []
        for file_path in file_path_list:
            surf = self.get_surface(file_path)
            surface_list.append(surf)
        return surface_list

    def get_light_surface(self, file_path):
        """
        获取高亮surface
        """
        # 如果图片已加载，直接返回surface
        if file_path in self.surface_light_pool:
            return self.surface_light_pool[file_path]
        surface = self.get_surface(file_path)
        light_surface = self.__init_light_surface(surface)
        self.surface_light_pool[file_path] = light_surface
        return light_surface

    def get_two_surface(self, file_path):
        """
        获取普通和高亮surface
        """
        surface = self.get_surface(file_path)
        light_surface = self.get_light_surface(file_path)
        return surface, light_surface

    def __init_light_surface(self, surface):
        # 初始化高亮表面
        light = 2  # 亮度
        t1 = time.time()
        surface = surface.copy()
        pixarr = pygame.PixelArray(surface)
        shape = pixarr.shape
        for x in range(shape[0]):
            for y in range(shape[1]):
                color = pixarr[x, y]
                b = color & 255
                gt = (color >> 8) & 255
                r = (color >> 16) & 255
                a = (color >> 24) & 255
                r1 = int(r * light)
                g1 = int(gt * light)
                b1 = int(b * light)
                if r1 > 255:
                    r1 = 255
                if g1 > 255:
                    g1 = 255
                if b1 > 255:
                    b1 = 255
                pixarr[x, y] = (r1, g1, b1, a)
        pixarr.close()
        t2 = time.time()
        print("生成表面耗时：", t2 - t1)
        return surface
